package fun.codefarmer.pm.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 *  * 第一步：类名CustomFilterInvocationSecurityMetadataSource 分析请求都具备哪些角色
 *  * 第二步：判断当前角色是否具备第一步中分析出的角色，如果具备，请求通过，否则请求步通过
 * @ ClassName CustomUrlDecisionManager
 * @ Descriotion TODO
 * @ author  codeFarmer_z
 * @ 公众号：码农教程
 * @ Date 2022/3/29 22:24
 **/
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {

    /**
     *
     * @param authentication 存储登录后的信息
     * @param object 请求对象，String requestUrl = ((FilterInvocation) object).getRequestUrl();
     * @param configAttributes 第一步中的返回值
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {//如果未匹配成功
                // 返回异常时，就是不通过。正常return 通过
                if (authentication instanceof AnonymousAuthenticationToken) {//如果当前用户是匿名用户实例，也就是未登录
                    throw new AccessDeniedException("尚未登录，请登录！");
                } else {
                    //
                    return;
                }
            }
            // 得到登录信息中的角色，符合其中任一角色，就可以访问
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员！");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
